package com.chang.soul.controller;

import com.alibaba.fastjson.JSONObject;
import com.chang.soul.bean.FileInfoBean;
import com.chang.soul.bean.ScaleBean;
import com.chang.soul.bean.ScaleQueryForm;
import com.chang.soul.conf.JwtIgnore;
import com.chang.soul.service.ScaleService;
import com.chang.soul.util.Result;
import com.chang.soul.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/scale")
@Api("量表管理接口")
public class ScaleController {
    @Autowired
    ScaleService scaleService;

    /*需要修改，与量表上传想关联*/
    @ApiOperation(value = "插入量表",notes = "无需token",httpMethod = "POST")
    @PostMapping("/insertScale")
    @JwtIgnore
    public Result insertScale(@Valid @RequestBody ScaleBean scaleBean){
        boolean flag = scaleService.insertScale(scaleBean);
        if(flag){
            return ResultUtil.success(scaleBean);
        }else{
            return ResultUtil.error("量表插入失败");
        }
    }

    @ApiOperation(value = "分页查询全部量表" ,notes="无需token",httpMethod = "POST")
    @PostMapping("/getAllScaleList")
    @JwtIgnore
    public Result getAllScaleList (@Valid @RequestBody ScaleQueryForm scaleQueryForm){
        Integer currentPage = scaleQueryForm.getCurrentPage();
        Integer pageSize = scaleQueryForm.getPageSize();
        currentPage = currentPage == null ||currentPage <= 0? 1 : currentPage;
        pageSize = pageSize == null || pageSize <=0 ?10 :pageSize;
        Integer startNum = (currentPage -1)*pageSize;
        scaleQueryForm.setCurrentPage(startNum);
        scaleQueryForm.setPageSize(pageSize);

        List<ScaleBean> list = scaleService.getAllScaleList(scaleQueryForm);
        System.out.println("list"+list);
        int total = scaleService.getCountByScaleList(scaleQueryForm);
        JSONObject res = new JSONObject();
        res.put("currentPage",currentPage);
        res.put("pageSize",pageSize);
        res.put("totalCount",total);
        res.put("list",list);

        System.out.println(res);
        return ResultUtil.success(res);
    }

    @ApiOperation(value = "通过id 删除量表",notes = "无需token",httpMethod = "GET")
    @GetMapping("/deleteScaleById")
    @JwtIgnore
    public Result deleteScaleById(@RequestParam(value = "id")Integer id){
        boolean flag = scaleService.deleteScaleById(id);
        if(!flag){
            return ResultUtil.error("delete scale fail");
        }
        return  ResultUtil.success("delete scale success");
    }

    @ApiOperation(value = "更新scale表",notes = "无需token",httpMethod = "POST")
    @PostMapping("/updateScale")
    @JwtIgnore
    public Result updateScale(@Valid @RequestBody ScaleBean myScaleBean){
        ScaleBean scaleBean = scaleService.getScaleById(myScaleBean.getId());
        scaleBean.setScaleName(myScaleBean.getScaleName());
        scaleBean.setScaleType(myScaleBean.getScaleType());

        if(scaleService.updateScale(scaleBean)){
            return ResultUtil.success(scaleBean);
        }else{
            return ResultUtil.error("update scale fail");
        }
    }


    /**
     * 获取一个文件夹下所有的文件名字
     */
    @ApiOperation(value = "获取文件夹下所有的文件",notes = "无需token",httpMethod = "POST")
    @PostMapping("/getScaleList")
    @JwtIgnore
    public Result getScaleList() {
        String path = "G:\\textFile";
        File file = new File(path);
        // get the folder list
        File[] array = file.listFiles();

        List<FileInfoBean>  ScaleList=new ArrayList<>();

        if(array.length>0){
            for (int i = 0; i < array.length; i++) {
                if (array[i].isFile()) {
                    System.out.println("^^^^^" + array[i].getName());
                    FileInfoBean fileInfo=new FileInfoBean();
                    fileInfo.setFileName(array[i].getName());
                    Long size= array[i].length();
                    fileInfo.setFileSize((size));
                    //返回文件最后修改时间，是以个long型毫秒数
                    long time= array[i].lastModified();
                    String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(time));
                    System.out.println(ctime);
                    fileInfo.setCreateTime(ctime);
                    ScaleList.add(fileInfo);
                } else if (array[i].isDirectory()) {
                    getFile(array[i].getPath());
                }
            }
            return ResultUtil.success(ScaleList);
        }else {
            return ResultUtil.error("文件夹为空，并没有文件可以下载！");
        }
    }
    @ApiOperation(value = "删除文件",notes = "无需token",httpMethod = "GET")
    @GetMapping("/deleteFile")
    @JwtIgnore
    public Result deleteFile(@RequestParam(value = "filename")String filename){
        System.out.println(filename);
        try {
            String filePath = "G:\\textFile\\";
            File file = new File(filePath + "/" + filename);
            if(file.exists()){
                file.delete();
            }else {
                ResultUtil.error("文件 不存在!");
            }

        }catch (Exception e){
            ResultUtil.error("delete fail!");
        }
        return ResultUtil.success("delete success!");
    }

    /**
     * 递归获取某路径下的所有文件，文件夹，并输出
     */
    private void getFile(String path) {
        // get file list where the path has
        File file = new File(path);
        // get the folder list
        File[] array = file.listFiles();

        for (int i = 0; i < array.length; i++) {
            if (array[i].isFile()) {
                // only take file name
                System.out.println("^^^^^" + array[i].getName());
                // take file path and name
                System.out.println("#####" + array[i]);
                // take file path and name
                System.out.println("*****" + array[i].getPath());
            } else if (array[i].isDirectory()) {
                getFile(array[i].getPath());
            }
        }
    }

    /**
     * 读取文件创建时间
     */
    public static void getCreateTime(){
        String filePath = "C:\\test.txt";
        String strTime = null;
        try {
            Process p = Runtime.getRuntime().exec("cmd /C dir "
                    + filePath
                    + "/tc" );
            InputStream is = p.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            while((line = br.readLine()) != null){
                if(line.endsWith(".txt")){
                    strTime = line.substring(0,17);
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("创建时间    " + strTime);
        //输出：创建时间   2009-08-17  10:21
    }
    /**
     * 读取文件修改时间的方法1
     */
    @SuppressWarnings("deprecation")
    public static void getModifiedTime_1(){
        File f = new File("C:\\test.txt");
        Calendar cal = Calendar.getInstance();
        long time = f.lastModified();
        cal.setTimeInMillis(time);
        //此处toLocalString()方法是不推荐的，但是仍可输出
        System.out.println("修改时间[1] " + cal.getTime().toLocaleString());
        //输出：修改时间[1]    2009-8-17 10:32:38
    }

    /**
     * 下载文件接口
     */
    @ApiOperation(value = "下载文件接口", notes = "需Token", httpMethod = "GET", produces = "application/octet-stream")
    @GetMapping("/download")
    @JwtIgnore
    public String down(@RequestParam(value = "filename")String filename, HttpServletResponse response) throws UnsupportedEncodingException {
        //获取项目的相对路径
//        String property = System.getProperty("user.dir");
//        String path = property + "/src/main/resources/static/";
//
////        String filename = "playlist.xlsx";

        String filePath = "G:\\textFile\\";
        File file = new File(filePath + "/" + filename);
        if (file.exists()) {
            System.out.println(filePath + "/" + filename + "存在");
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "utf8"));
            byte[] buffer = new byte[1024];
            //输出流
            OutputStream os = null;
            try (FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fis);) {
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
                return "success!";
            } catch (Exception e) {
                e.printStackTrace();
                return "fail!";
            }
        } else {
            return "fail!";
        }
    }

}


